package cn.lj.user.Interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component/*交给spring管理*/
public class LoginInterceptor implements HandlerInterceptor{
    /*自定义拦截器：1.实现HandlerInterceptor
    *               2.实现HandlerInterceptor接口
    *               3.重写preHandle方法
    * */
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //*3.1   获取前台请求的表示符*//*
        String token = request.getHeader("token");
        //*3.2   校验token是否存在*//*
        //*StringUtils.isEmpty(token)：token是否为空，不为空返回false,为空返回true*//*
        if(!StringUtils.isEmpty(token)){//*token存在*//*
            //*3.3   通过前台token获取redis里的登录信息*//*
            Object loginTemp = redisTemplate.opsForValue().get(token);
            //*3.4   比较*//*
            if(loginTemp != null){
                //*重新设置缓存时间*//*
                redisTemplate.opsForValue().set(token,loginTemp,30, TimeUnit.MINUTES);
                //*放行*//*
                return true;
            }
        }
        //*4.    当token空，禁止通行，返回json数据格式给前台，并且跳转login页面*//*
        response.setContentType("application/json;charset=utf-8");

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":\"false\",\"message\":\"noLogin\"}");
        writer.close();//字符流要关闭
        return false;
    }
}
